<!-- out-store -->
<template>
    <div class="main-content out-content store-content">
        <page-header></page-header>
        <el-steps :active="active" finish-status="success">
            <el-step title="身份识别"></el-step>
            <el-step title="选择类型"></el-step>
            <el-step title="清点设备"></el-step>
            <el-step title="出库完成"></el-step>
        </el-steps>
        <div class="out-store-content">
            <div class="top" :style="topSty">
                <component 
                :tb1="tb1"
                :tb2="tb2"
                :temName="temName"
                :is="who" 
                @getnext="getGoNext"
                @addActive="addActive"></component>
            </div>
            <div class="bottom" v-if="who!='out-store-menus'">
                <el-button 
                @click="confirmOutStore"
                :disabled="btnDis"
                :loading="load"
                class="done-btn">出库</el-button>
                <el-button 
                @click="handleClickBtn"
                class="check-btn">{{btnVal}}</el-button>
            </div>
            
        </div>
        <el-dialog
        :visible.sync="centerDialogVisible"
        width="25%"
        center>
        <span>确定将设备出库？</span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    getListByTem,
    requestOutStore
} from '@/apis'
export default {
    name: 'out-store',
    components: {
        'page-header': () => import('@/components/page-header'),
        'out-store-menus': () => import('@/components/out/out-store-menus'),
        'check-devs': () => import('@/components/out/check-devs'),
        'user-reco': () => import('@/components/out/user-reco'),
    },
    data () {
        return {
            btnDis: true,
            active: 1,
            who: 'user-reco',
            centerDialogVisible: false,
            tb1: [],
            toolCodeAry: [],
            temName: '',
            btnVal: '开始清点',
            timer: null,
            timer1: null,
            load: false
        }
    },
    watch: {
        active (newVal, oldVal) {
            if (newVal == 4) return;
            let cmps = ['user-reco', 'out-store-menus', 'check-devs']
            this.who = cmps[newVal-1];
        }
    },
    computed: {
        topSty () {
            let obj;
            if (this.who == 'out-store-menus' || this.who == 'user-reco') {
                obj = {
                    height: '100%'
                }
            } else {
                obj = {
                    height: 'calc(100% - 170px)',
                    paddingTop: '32px'
                }    
            }
            return obj
        },
        tb2 () {
            let tools = JSON.parse(sessionStorage.getItem('devs'));
            return this.toolCodeAry.map(dev => {
                let _item;
                tools.forEach(tool => {
                    if (tool.toolCode == dev) {
                        _item = tool 
                    } 
                
                })
                
                return _item
            })
        },
        url1 () {
            return `https://localhost:8862`
            //return '/local'
        }
    },
    methods: {
        // 获取下个页面的标志
        getGoNext (val) {
            this.active = val.step;
            this.temName = val.name;
            this.getListByTemplateId(val.id);
        },

        // 进行下一页
        addActive (val) {
            this.active = val.step;
        },

        // 获取作业模板下的所有器具列表
        async getListByTemplateId (id) {
            try {
                let res = await getListByTem(id);
                console.log('获取作业模板下的所有器具列表', res);
                let {
                    code,
                    msg,
                    data
                } = res.data;
                if (code == 200) {
                    this.tb1 = data;
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});    
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                }
            } catch(e) {
                console.log('获取作业模板下的所有器具列表',e)
            }
        },

        // 点击按钮
        handleClickBtn () {
            this.btnDis = true;
            if (this.btnVal == '开始清点' || this.btnVal == '重新清点') {
                this.startCheck();
            } else if (this.btnVal == '结束清点') {
                this.stopCheck();
            }
        },

        // 开始清点
        startCheck () {
            this.$axios.get(this.url1 + '/startCheck').then(res => {
                console.log('清点数据', res);
                this.checkFlag = 1;
                this.btnVal = '结束清点';
                this.timer && window.clearInterval(this.timer);
                this.timer = setInterval(() => {
                    this.recevieData();
                }, 1000)
            })
        },

        // 获取清点数据
        recevieData () {
            this.$axios.get(this.url1 + '/getTagData').then(res => {
                let devs = res.data;
                this.toolCodeAry = Array.from(new Set([...this.toolCodeAry, ...devs]))
            })
        },

        // 结束清点
        stopCheck () {
            this.$axios.get(this.url1 + '/stopCheck').then(res => {
                console.log('结束清点', res);
                this.checkFlag = 0;
                this.btnVal = '重新清点';
                this.btnDis = false;
                this.clearTImer();
            })
        },

        // 确认出库
        confirmOutStore () {
            this.$confirm('确认出库吗？')
            .then(_ => {
                this.handleOutStore();
            })
            .catch(_ => {});
            
        },

        // 出库 请求
        async handleOutStore () {
            try {
                this.load = true;
                let deptId = window.localStorage.getItem('organizationId');
                let params = {
                    outTools: this.toolCodeAry.map(code => {
                        return {
                            toolCode: code
                        }
                    }),
                    operateDept: deptId, // 部门id 99
                    jobTypeName: this.temName
                }
                let res = await requestOutStore(params);
                console.log('出库 -- 请求', res);
                let {
                    code,
                    msg
                } = res.data;
                if (code == 200) {
                    this.active = 3;
                    this.$message({
                        type: 'success',
                        message: `出库成功`
                    })
                    this.load = false;
                    this.timer1 && clearTimeout(this.timer1);
                    this.timer1 = setTimeout(() => {
                        this.$router.replace('/home').catch({})
                    }, 2000)
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                    this.load = false;  
                } else {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.load = false;
                }
            } catch(e) {
                console.log('requestOutStore',e)
                this.load = false;
            }
        },

        // 清除定时器
        clearTImer () {
            if (this.timer) {
                window.clearInterval(this.timer);
                this.timer = null;
            }
        }

    },
    created () {
        this.checkFlag = 0;
    },
    beforeRouteLeave(to, from, next) {
        console.log('this.checkFlag', this.checkFlag, this.checkFlag != 0)
        if (this.checkFlag != 0) {
            this.stopCheck();
        }
        this.timer && clearInterval(this.timer);
        this.timer1 && clearInterval(this.timer1);
        this.timer = null;
        this.timer1 = null;
        next();  
    }
}
</script>
<style lang='scss'>
.out-content {
    .el-dialog {
        margin-top: 35vh!important;
        background: #3D4E69;
        border-radius: 14px;

        .el-dialog__body {
            font-size: 36px;
            color: #FFFFFF;
            letter-spacing: 0;
            font-weight: 400;
        }
        
    }
}
.out-store-content {
    width: 100%;
    height: calc(100% - 146px);
    box-sizing: border-box;

    .bottom {
        height: 80px;
        padding-bottom: 26px;
        padding-top: 32px;

        .check-btn {
            width: 390px;
            height: 80px;
            background: #2683FF;
            border-radius: 4px;
            float: right;
            margin-right: 42px;
            border-color: #2683FF;
            font-size: 40px;
            color: #FFFFFF;
            letter-spacing: 0;
            font-weight: 400;
        }

        .done-btn {
            width: 252px;
            height: 80px;
            background: #2683FF;
            border-radius: 4px;
            float: right;
            border-color: #2683FF;
            font-size: 40px;
            color: #FFFFFF;
            letter-spacing: 0;
            font-weight: 400;
        }
    }
    
}
</style>